package com.cat.DataStructure04;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author 曲大人的喵
 * @description https://leetcode.cn/problems/reconstruct-a-2-row-binary-matrix/
 * @create 2025/11/27 20:11
 * @since JDK17
 */

public class Solution22 {
    public List<List<Integer>> reconstructMatrix(int upper, int lower, int[] colsum) {
        int n = colsum.length, sum = Arrays.stream(colsum).sum();
        List<List<Integer>> ans = new ArrayList<>();
        if (sum != upper + lower) {
            return ans;
        }
        sum = 0;
        List<Integer> l1 = new ArrayList<>(), l2 = new ArrayList<>();
        int[] t1 = new int[n], t2 = new int[n];
        for (int i = 0; i < n; i++) {
            int x = colsum[i];
            if (x == 2 && upper > 0 && lower > 0) {
                t1[i] = 1;
                t2[i] = 1;
                upper--;
                lower--;
                x = 0;
            }
            if (x == 1) {
                if (lower >= upper && lower > 0) {
                    t2[i] = 1;
                    lower--;
                    x = 0;
                } else if (upper > 0){
                    t1[i] = 1;
                    upper--;
                    x = 0;
                }
            }
            sum += x;
        }
        if (sum != 0 || lower != 0 || upper != 0) {
            return ans;
        }
        for (int i = 0; i < n; i++) {
            l1.add(t1[i]);
            l2.add(t2[i]);
        }
        ans.add(l1);
        ans.add(l2);
        return ans;
    }
}
